-module(fermat).
-export([p1/0, p1_ho/0, p2/0, p3/0, p4/0, p5/0, p6/0, p7/0]).


%% Problem 1
p1() -> p1(lists:seq(0,999), 0).

p1([H|T],N) when (H rem 3 =:= 0) or (H rem 5 =:= 0) -> p1(T, N+H);
p1([_|T],N) -> p1(T,N);
p1([],N) -> N.

p1_ho() -> lists:sum(lists:filter(fun(X)->((X rem 3 =:= 0) or (X rem 5 =:= 0)) end, lists:seq(0, 999))).


%% Problem 2
p2() -> p2(1, 2, 4000000, 0).

p2(X1, X2, Total,Sum) when X2 < Total ->
	case (X2 rem 2) of
		0 -> p2(X2, X1+X2, Total, Sum+X2);
		1 -> p2(X2, X1+X2, Total, Sum)
	end;
p2(_, _, _, Sum) -> Sum.


%% Problem 3
p3() -> p3(600851475143).
p3(X) -> get_first_prime(mylib:factor(X)).

get_first_prime([H|T]) ->
	case mylib:is_prime(H) of
		true -> H;
		false -> get_first_prime(T)
	end;
get_first_prime([]) ->
	ok.

%% Problem 4

p4() ->
	[H|_] = (lists:reverse(lists:sort(lists:filter(fun(X)->mylib:is_palindrome(integer_to_list(X)) end,[ X*Y || X<-lists:seq(100,1000), Y<-lists:seq(100,1000) ])))),
	H.


%% Problem 5
p5() -> p5(2521, lists:reverse(lists:seq(11, 20))).

p5(Num, Divisors) ->			
	case mylib:is_divisible_by_all(Num, Divisors) of
		true -> Num;
		false -> p5(Num+1, Divisors)
	end.

				
%% Problem 6
p6() -> p6(lists:seq(1, 100)).

p6(List) ->
	SumOfSquare = lists:sum(lists:map(fun(X)->X*X end, List)),
	SquareOfSum = math:pow(lists:sum(List), 2),
	SquareOfSum - SumOfSquare.


%% Problem 7
p7() -> p7(1, 10001, 2).

p7(Start, Num, Current) when Start < Num ->
	NewCurrent = Current + 1,
	case mylib:is_prime(NewCurrent) of
		true ->
			p7(Start+1, Num, NewCurrent);
		false -> 
			p7(Start, Num, NewCurrent)
	end;
p7(Num, Num, Current) -> Current.

	